import os
import subprocess
import logging

logger = logging.getLogger("bgw")


def execute_script(script_path):
    """执行shell脚本"""
    try:
        if not os.path.exists(script_path):
            logger.error(f"脚本文件不存在: {script_path}")
            return {"_status": 1, "_msg": f"脚本文件不存在: {script_path}"}
        
        # 确保脚本有执行权限
        os.chmod(script_path, 0o755)
        
        # 执行脚本
        result = subprocess.run(
            [script_path], 
            capture_output=True, 
            text=True, 
            timeout=30  # 30秒超时
        )
        
        if result.returncode == 0:
            logger.info(f"脚本执行成功: {script_path}")
            return {
                "_status": 0, 
                "_msg": "执行成功", 
                "output": result.stdout.strip()
            }
        else:
            logger.error(f"脚本执行失败: {script_path}, 错误: {result.stderr}")
            return {
                "_status": 1, 
                "_msg": f"脚本执行失败: {result.stderr}"
            }
            
    except subprocess.TimeoutExpired:
        logger.error(f"脚本执行超时: {script_path}")
        return {"_status": 1, "_msg": "脚本执行超时"}
    except Exception as e:
        logger.error(f"执行脚本时发生异常: {str(e)}")
        return {"_status": 1, "_msg": f"执行脚本时发生异常: {str(e)}"}

